<?php
namespace Hilaoyu\LaravelExtend\Providers;

use Hilaoyu\LaravelExtend\Providers\RequestMacroServiceProvider;
use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\LaravelExtend\Services\Auth\Redefinition\DatabaseUserWithMultipleAuthTokenProvider;
use Hilaoyu\LaravelExtend\Services\Auth\Redefinition\EloquentUserWithMultipleAuthTokenProvider;
use Hilaoyu\LaravelExtend\Services\Auth\Redefinition\TokenGuard;
use Hilaoyu\LaravelExtend\Supports\SubApp;
use Hilaoyu\LaravelPrivateApi\PrivateApiService;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Support\ServiceProvider;
use Event;


class AuthServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([dirname(__DIR__).'/Services/Auth/database/migrations' => database_path('migrations')], 'laravel-extend-auth');
        //$this->loadMigrationsFrom(dirname(__DIR__).'/Services/Auth/database/migrations');



        /*Event::listen('Illuminate\Auth\Events\Authenticated', function ($event) {
            UtilSupport::tryQuiet(function () use ($event){
                AuthService::LoginRefresh($event->user,$event->guard);
            });
        });*/
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

        app()->register(RequestMacroServiceProvider::class);

        $this->app['auth']->extend('token',function($app,$name, $config)
        {
            return new TokenGuard(
                $app['auth']->createUserProvider($config['provider'] ?? null),
                $app['request']
            );
        });

        $this->app['auth']->provider('eloquent',function($app,$config)
        {
            return new EloquentUserWithMultipleAuthTokenProvider(
                $app['hash'],
                $config['model']
            );
        });

        SubApp::registerCommands(dirname(__DIR__).'/Services/Auth/Console','Hilaoyu\\LaravelExtend\\Services\\Auth\\Console');

        SubApp::registerRoutes(dirname(__DIR__) . '/Services/Auth/routes','Hilaoyu\\LaravelExtend\\Services\\Auth\\Controllers',[
            'name'=>'l-e-s.auth',
            'prefix'=> config('auth.route_prefix','_les/auth'),
            'middleware'=> config('auth.route_middleware',[]),
        ]);

        foreach (config('auth.providers', '') as $provider_config){
            if(data_get($provider_config,'provide_service')){
                PrivateApiService::regiserRoutes(dirname(__DIR__) . '/Services/Auth/private_service_routes','Hilaoyu\\LaravelExtend\\Services\\Auth\\Controllers',[
                    'name'=>'l-e-s.auth.service'
                ]);
                break;
            }
        }

    }


}
